package com.ruoyi.business.payment.service.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.business.approvalflow.domain.TRegisterApprovalFlow;
import com.ruoyi.business.approvalflow.enums.ApprovalFlowStatus;
import com.ruoyi.business.approvalflow.enums.ApprovalProcessDefine;
import com.ruoyi.business.approvalflow.vo.TRegisterApprovalFlowVo;
import com.ruoyi.business.domain.TRegisterNotice;
import com.ruoyi.business.enums.PayStatusEnums;
import com.ruoyi.business.mapper.TRegisterInfoMapper;
import com.ruoyi.business.payment.config.PaymentConfig;
import com.ruoyi.business.payment.domain.*;
import com.ruoyi.business.payment.enums.*;
import com.ruoyi.business.payment.mapper.TRegisterPaymentOrderMapper;
import com.ruoyi.business.approvalflow.service.ITRegisterApprovalFlowService;
import com.ruoyi.business.payment.service.ITRegisterPaymentOrderService;
import com.ruoyi.business.payment.service.IThirdPaymentService;
import com.ruoyi.business.payment.utils.IdGeneratorUtils;
import com.ruoyi.business.payment.vo.*;
import com.ruoyi.business.service.ITRegisterNoticeService;
import com.ruoyi.business.vo.TRegisterInfoVo;
import com.ruoyi.business.vo.TRegisterNoticeVo;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 预支付订单信息Service业务层处理
 *
 * @author Tellsea
 * @date 2025-06-22
 */
@Service
@Slf4j
public class TRegisterPaymentOrderServiceImpl extends ServiceImpl<TRegisterPaymentOrderMapper, TRegisterPaymentOrder> implements ITRegisterPaymentOrderService {

    @Autowired
    private IThirdPaymentService thirdPaymentService;

    @Autowired
    private ITRegisterApprovalFlowService flowService;

    @Autowired
    private TRegisterInfoMapper registerInfoMapper;

    @Autowired
    private ITRegisterNoticeService registerNoticeService;

    @Autowired
    private PaymentConfig paymentConfig;


    @Override
    public TableDataInfo<TRegisterPaymentOrderDto> queryList(TRegisterPaymentOrderVo entity) {
        Page<Object> pager = new Page<>(entity.getPageNum(), entity.getPageSize());
        Page<TRegisterPaymentOrderDto> orderDtoPage = this.baseMapper.queryList(pager, entity);
        List<Long> registerIdList = new ArrayList<>();
        List<String> businessIdList = new ArrayList<>();
        List<TRegisterPaymentOrderDto> records = orderDtoPage.getRecords();
        for (TRegisterPaymentOrderDto orderDto : records) {
            registerIdList.add(orderDto.getRegisterId());
            if (StringUtils.isNotEmpty(orderDto.getRefundId())) {
                businessIdList.add(orderDto.getRefundId());
            }
        }
        if (!registerIdList.isEmpty()) {
            // 查询注册报名信息
            TRegisterInfoVo registerInfoVo = new TRegisterInfoVo();
            registerInfoVo.setRegisterIdList(registerIdList);
            List<TRegisterInfoVo> tRegisterInfos = registerInfoMapper.queryList(registerInfoVo);
            Map<Long, TRegisterInfoVo> tRegisterInfoMap = tRegisterInfos.stream()
                    .collect(Collectors.toMap(
                            TRegisterInfoVo::getId,
                            Function.identity(),
                            (oldVal, newVal) -> oldVal
                    ));
            // 查询通知信息
            QueryWrapper<TRegisterNotice> noticeWrapper = new QueryWrapper<>();
            noticeWrapper.in("register_id", registerIdList);
            List<TRegisterNotice> registerNotices = registerNoticeService.list(noticeWrapper);
            Map<Long, TRegisterNotice> tRegisterNoticeMap = registerNotices.stream()
                    .collect(Collectors.toMap(
                            TRegisterNotice::getRegisterId,
                            Function.identity(),
                            (oldVal, newVal) -> oldVal
                    ));

            // 查询审批流程数据
            List<TRegisterApprovalFlowVo> flowVoList = new ArrayList<>();
            if (!businessIdList.isEmpty()) {
                flowVoList = flowService.queryWaitApprove(ApprovalProcessDefine.PAY_REFUND.getId(), businessIdList, entity.getUserId());
            }
            Map<String, TRegisterApprovalFlowVo> tRegisterApproveMap = flowVoList.stream()
                    .collect(Collectors.toMap(
                            TRegisterApprovalFlowVo::getBusinessId,
                            Function.identity(),
                            (oldVal, newVal) -> oldVal
                    ));

            // 查询审批流程数据
            List<TRegisterApprovalFlowVo> flowVoList1 = new ArrayList<>();
            if (!businessIdList.isEmpty()) {
                flowVoList1 = flowService.queryWaitApprove(ApprovalProcessDefine.PAY_REFUND.getId(), businessIdList);
            }
            Map<String, TRegisterApprovalFlowVo> tRegisterApproveMap1 = flowVoList1.stream()
                    .collect(Collectors.toMap(
                            TRegisterApprovalFlowVo::getBusinessId,
                            Function.identity(),
                            (oldVal, newVal) -> oldVal
                    ));

            // 循环填充数据
            for (TRegisterPaymentOrderDto paymentOrderDto : records) {
                paymentOrderDto.setRegisterInfo(tRegisterInfoMap.get(paymentOrderDto.getRegisterId()));
                paymentOrderDto.setRegisterNotice(tRegisterNoticeMap.get(paymentOrderDto.getRegisterId()));
                if (StringUtils.isNotEmpty(paymentOrderDto.getRefundId())
                        && tRegisterApproveMap.get(paymentOrderDto.getRefundId())!=null) {
                    paymentOrderDto.setIfCanApprove(true);
                }
                TRegisterApprovalFlowVo approvalFlowVo = tRegisterApproveMap1.get(paymentOrderDto.getRefundId());
                if(approvalFlowVo!=null){
                    paymentOrderDto.setRegisterApprovalFlow(approvalFlowVo);
                }
            }

        }
        return PageUtils.buildDataInfo(orderDtoPage);
    }

    @Override
    public List<TRegisterPaymentOrderDto> queryAll(TRegisterPaymentOrderVo entity) {
        return this.baseMapper.queryList(entity);
    }

    @Override
    public TableDataInfo<TRegisterPaymentOrderDeptDto> queryByDept(TRegisterPaymentOrderVo entity) {
        Page<Object> pager = new Page<>(entity.getPageNum(), entity.getPageSize());
        Page<TRegisterPaymentOrderDeptDto> orderDtoPage = this.baseMapper.queryByDept(pager, entity);
        return PageUtils.buildDataInfo(orderDtoPage);
    }

    @Override
    public TRegisterPaymentOrderDto queryById(Long orderId) {
        TRegisterPaymentOrderDto paymentOrderDto = this.baseMapper.queryById(orderId);
        if (paymentOrderDto == null) {
            return null;
        }
        handlePayOrderDetail(paymentOrderDto);

        return paymentOrderDto;
    }

    @Override
    public TRegisterPaymentOrderDto queryByRegisterId(Long registerId) {
        TRegisterPaymentOrderDto paymentOrderDto = this.baseMapper.queryByRegisterId(registerId);
        if (paymentOrderDto == null) {
           return null;
        }
        handlePayOrderDetail(paymentOrderDto);

        return paymentOrderDto;
    }

    /**
     * 处理支付订单详情
     * @param paymentOrderDto q
     */
    private void handlePayOrderDetail(TRegisterPaymentOrderDto paymentOrderDto) {
        if (paymentOrderDto.getRefundStatus() != null
                && (paymentOrderDto.getRefundStatus() == OrderRefundStatus.PENDING_APPROVAL.getCode()
                || paymentOrderDto.getRefundStatus() == OrderRefundStatus.IN_APPROVAL.getCode())) {
            Long userId = SecurityUtils.getLoginUser().getUserId();
            List<TRegisterApprovalFlowVo> flowVoList = flowService.queryWaitApprove(ApprovalProcessDefine.PAY_REFUND.getId(), Collections.singletonList(paymentOrderDto.getRefundId()), userId);
            if (!flowVoList.isEmpty()) {
                paymentOrderDto.setIfCanApprove(true);
            }
            List<TRegisterApprovalFlowVo> approvalFlowVos = flowService.queryWaitApprove(ApprovalProcessDefine.PAY_REFUND.getId(), Collections.singletonList(paymentOrderDto.getRefundId()));
            if (!approvalFlowVos.isEmpty()) {
                paymentOrderDto.setRegisterApprovalFlow(approvalFlowVos.get(0));
            }
        }
        TRegisterInfoVo tRegisterInfoVo = registerInfoMapper.queryById(paymentOrderDto.getRegisterId());
        paymentOrderDto.setRegisterInfo(tRegisterInfoVo);

        TRegisterNoticeVo tRegisterNoticeVo = registerNoticeService.queryByRegisterId(paymentOrderDto.getRegisterId());
        paymentOrderDto.setRegisterNotice(tRegisterNoticeVo);
    }

    @Override
    public TRegisterPaymentOrderStatDto queryByStat(TRegisterPaymentOrderVo entity) {
        return this.baseMapper.queryByStat(entity);
    }

    @Override
    public void closeOrder(Long orderId) throws Exception {
        TRegisterPaymentOrderDto order = queryById(orderId);
        if (order == null) {
            throw new BaseException("订单不存在");
        }
        // 校验订单状态
        if (order.getPaymentStatus() != PaymentOrderStatus.PENDING_PAYMENT.getCode()) {
            throw new BaseException("订单状态不合法: 订单不是待支付状态");
        }
//        JSONObject submitJson = new JSONObject();
//        submitJson.put("busNo", String.valueOf(order.getId()));
//        submitJson.put("busDate", DateUtil.format(order.getCreateTime(), "yyyy-MM-dd"));
//        thirdPaymentService.submitCloseOrder(submitJson.toJSONString());
        // 修改订单状态
        order.setPaymentStatus(PaymentOrderStatus.CLOSED.getCode());
        baseMapper.updateById(order);
    }

    /**
     * 创建预支付订单
     */
    @Transactional
    @Override
    public Long createPrePaymentOrder(Long registerId) throws Exception {
        QueryWrapper<TRegisterPaymentOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.notIn("payment_status",
                PaymentOrderStatus.CLOSED.getCode(),
                PaymentOrderStatus.PAID.getCode(),
                PaymentOrderStatus.REFUNDED.getCode());
        queryWrapper.eq("register_id", registerId);
        Integer sCnt = baseMapper.selectCount(queryWrapper);
        if (sCnt != null && sCnt > 0) {
            throw new BaseException("预支付下单已提交，不可再次提交");
        }
        TRegisterInfoVo registerInfo = registerInfoMapper.queryById(registerId);
        if (registerInfo == null) {
            throw new BaseException("报名信息不存在");
        }
        TRegisterNoticeVo tRegisterNoticeVo = registerNoticeService.queryByRegisterId(registerId);
        if (tRegisterNoticeVo == null) {
            throw new BaseException("进修通知书未发送");
        }
        // 3. 创建订单
        TRegisterPaymentOrder order = new TRegisterPaymentOrder();
        order.setId(IdGeneratorUtils.generateOrderId());
        order.setRegisterId(registerId);
        order.setUserName(registerInfo.getUserName());
        order.setPhoneNumber(registerInfo.getPhoneNumber());
        order.setIdCard(registerInfo.getIdCard());
        order.setPaymentStatus(PaymentOrderStatus.PENDING_PAYMENT.getCode());
        order.setCreateTime(DateUtils.getNowDate());
        order.setEngageAmount(tRegisterNoticeVo.getEngageMoney() == null ? new BigDecimal(0) : tRegisterNoticeVo.getEngageMoney());
        order.setMaterialAmount(tRegisterNoticeVo.getMaterialMoney() == null ? new BigDecimal(0) : tRegisterNoticeVo.getMaterialMoney());
        if (registerInfo.getJoinMicrosutureTrain() != null && registerInfo.getJoinMicrosutureTrain() == 1) {
            order.setJoinMicrosutureAmount(new BigDecimal(2800));
        } else {
            order.setJoinMicrosutureAmount(new BigDecimal(0));
        }
        order.setPayDataType(PaymentTypeStatus.NOPAY.getCode());
        order.setPaymentAmount(order.getEngageAmount().add(order.getMaterialAmount()).add(order.getJoinMicrosutureAmount() == null ? new BigDecimal(0) : order.getJoinMicrosutureAmount()));
        // 6.提交订单到支付中心
        JSONObject submitJson = new JSONObject();
        submitJson.put("busNo", String.valueOf(order.getId()));
        submitJson.put("busDateTime", DateUtil.format(new Date(), "yyyyMMddHHmmssSSS"));
        submitJson.put("payer", order.getUserName());
        submitJson.put("tel", order.getPhoneNumber());
        submitJson.put("idCardNo", order.getIdCard());
        submitJson.put("idCardType", "1101");
        submitJson.put("amount", order.getPaymentAmount());
        submitJson.put("notifyUrl", paymentConfig.getPayNotifyUrl());
        /**
         * 02	微信支付原生二维码图片Base64
         * 03	PC端H5收银台
         * 04	业务订单号
         * 05	融合码
         * 06	【微信】公众号支付
         * 07	【微信】小程序支付
         * 08	【支付宝】小程序支付
         * 09	【支付宝】服务窗--暂不支持
         * 10	线下支付
         */
        submitJson.put("payDataType", paymentConfig.getPayDataType());
        /**
         * WX	微信支付	线上支付
         * ALI	支付宝支付	线上支付
         * OFFLINE_CASH	现金	线下支付
         * OFFLINE_TRANSFER	汇款转账	线下支付
         * OFFLINE_POS	POS机	线下支付
         * OFFLINE_WX	微信（线下）	线下支付
         * OFFLINE_ALI	支付宝（线下）	线下支付
         */
        /*submitJson.put("payChannelCode", "OFFLINE_CASH");
        submitJson.put("taxType", "1");
        submitJson.put("taxRise", "测试开票抬头名称");
        submitJson.put("taxPayerIdCode", order.getIdCard());
        submitJson.put("taxRegisterAddr", "注册地址");
        submitJson.put("taxRegisterTel", "021811111");
        submitJson.put("taxOpBank", "中国银行");
        submitJson.put("taxBankAccount", "021811111");*/

        submitJson.put("operator", paymentConfig.getOperator());
        submitJson.put("templateCode", paymentConfig.getTemplateCode());
        JSONArray chargeDetailArr = new JSONArray();
        JSONObject chargeDetail = new JSONObject();
        chargeDetail.put("chargeCode", paymentConfig.getChargeCode());
        chargeDetail.put("chargeName", paymentConfig.getChargeName());
        chargeDetail.put("std", order.getPaymentAmount());
        chargeDetail.put("number", 1);
        chargeDetail.put("amt", order.getPaymentAmount());
        chargeDetailArr.add(chargeDetail);
        order.setChargeDetail(chargeDetailArr.toJSONString());
        submitJson.put("chargeDetail", chargeDetailArr);
        thirdPaymentService.submitPrePayOrder(submitJson.toJSONString());
        // 5. 保存订单
        baseMapper.insert(order);
        // 修改进修主表为待支付
        registerInfo.setPayStatus(PayStatusEnums.NO.getCode());
        registerInfoMapper.updateById(registerInfo);
        return order.getId();
    }

    /**
     * 处理支付回调
     */
    @Transactional
    @Override
    public void handlePaymentCallback(Long orderId, String channelOrderNo, String payChannelOrderNo,
                                      BigDecimal amount, Date paymentDate, boolean isOnline) {
        log.info("第三方回调开始，订单Id:"+orderId+",channelOrderNo:"+channelOrderNo+",payChannelOrderNo:"+payChannelOrderNo+",amount:"+amount
        +",paymentDate:"+paymentDate+",isOnline"+isOnline);
        TRegisterPaymentOrderDto order = baseMapper.queryById(orderId);
        if (order == null) {
            throw new BaseException("订单不存在");
        }
        // 校验订单状态
//        if (order.getPaymentStatus() != PaymentOrderStatus.PENDING_PAYMENT.getCode()) {
//            throw new BaseException("订单状态不合法: " + order.getPaymentStatus());
//        }
        BigDecimal scaledNum1 = amount.setScale(2, RoundingMode.HALF_UP); // 10.01
        BigDecimal scaledNum2 = order.getPaymentAmount().setScale(2, RoundingMode.HALF_UP); // 10.00
        if (scaledNum1.compareTo(scaledNum2) != 0) {
            throw new BaseException("订单支付金额不一致");
        }
        order.setUpdateTime(DateUtils.getNowDate());
        // 支付成功
        order.setPaymentStatus(PaymentOrderStatus.PAID.getCode());
        order.setPaymentTime(paymentDate);
        order.setChannelPaymentNo(payChannelOrderNo);
        order.setChannelOrderNo(channelOrderNo);
        order.setPayDataType(isOnline ? PaymentTypeStatus.ONLINE.getCode() : PaymentTypeStatus.OFFLINE.getCode());
        // 更新订单
        baseMapper.updateById(order);
        // 修改进修表的状态 PayStatusEnums
        TRegisterInfoVo registerInfo = registerInfoMapper.queryById(order.getRegisterId());
        if (registerInfo == null) {
            throw new BaseException("报名信息不存在");
        }
        registerInfo.setPayStatus(PayStatusEnums.SUCCESS.getCode());
        registerInfoMapper.updateById(registerInfo);
    }

    /**
     * 处理退款回调
     */
    @Transactional
    @Override
    public void handleRefundCallback(String busNo, String refundBusNo, String channelRefundNo, BigDecimal refundAmount, Date refundDate) {
        QueryWrapper<TRegisterPaymentOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("refund_id", refundBusNo);
        List<TRegisterPaymentOrder> orderList = baseMapper.selectList(queryWrapper);
        if (orderList == null || orderList.isEmpty()) {
            throw new BaseException("订单不存在");
        }
        TRegisterPaymentOrder order = orderList.get(0);
        // 校验订单状态
//        if (order.getPaymentStatus() != PaymentOrderStatus.REFUNDING.getCode()) {
//            throw new BaseException("订单不属于退款中状态或者已退款");
//        }
        BigDecimal scaledNum1 = refundAmount.setScale(2, RoundingMode.HALF_UP); // 10.01
        BigDecimal scaledNum2 = order.getRefundAmount().setScale(2, RoundingMode.HALF_UP); // 10.00
        if (scaledNum1.compareTo(scaledNum2) != 0) {
            throw new BaseException("订单退款金额不一致");
        }
        // 根据支付结果更新订单状态
        order.setUpdateTime(DateUtils.getNowDate());
        // 更新申请状态
        order.setRefundStatus(OrderRefundStatus.COMPLETED.getCode());
        order.setRefundTime(refundDate);
        order.setChannelRefundNo(channelRefundNo);
        order.setPaymentStatus(PaymentOrderStatus.REFUNDED.getCode());
        baseMapper.updateById(order);
        // 修改进修表的状态 PayStatusEnums
        TRegisterInfoVo registerInfo = registerInfoMapper.queryById(order.getRegisterId());
        if (registerInfo == null) {
            throw new BaseException("报名信息不存在");
        }
        registerInfo.setPayStatus(PayStatusEnums.REFUND.getCode());
        registerInfoMapper.updateById(registerInfo);
    }

    /**
     * 提交退款申请
     */
    @Transactional
    @Override
    public void addRefundApply(Long orderId, BigDecimal amount, String reason) throws ParseException {
        TRegisterPaymentOrderDto order = baseMapper.queryById(orderId);
        if (order == null) {
            throw new BaseException("订单不存在");
        }
        // 校验订单状态
        if (order.getPaymentStatus() != PaymentOrderStatus.PAID.getCode()
                || order.getRefundStatus() != null) {
            throw new BaseException("订单状态不允许退款: 订单不处于已支付状态或者已有退款");
        }
//        TRegisterNoticeVo tRegisterNoticeVo = registerNoticeService.queryByRegisterId(order.getRegisterId());
//        String startDate = tRegisterNoticeVo.getStartDate();
//        LocalDateTime date = DateUtil.parseLocalDateTime(startDate, "yyyy/MM/dd");
//        if (LocalDate.now().isAfter(ChronoLocalDate.from(date.plusWeeks(2)))) {
//            throw new BaseException("当前申请单无法办理退款，进修退款仅可在进修“确认报到”后两周内提交申请，逾期将不予受理");
//        }
        // 创建退款申请
        order.setRefundId(String.valueOf(IdGeneratorUtils.generateRefundId()));
        order.setRefundAmount(amount);
        order.setRefundReason(reason);
        order.setRefundTime(DateUtils.getNowDate());
        order.setRefundStatus(OrderRefundStatus.PENDING_APPROVAL.getCode());
        // 保存申请
        this.baseMapper.updateById(order);

        // 创建审批流程
        flowService.initApprovalFlows(ApprovalProcessDefine.PAY_REFUND.getId(), order.getRefundId(), order.getRegisterId());

    }

    @Transactional
    @Override
    public void queryForTimeOutOrder() throws Exception {
        List<TRegisterPaymentOrderVo> orderVoList = baseMapper.queryForTimeOutOrder();
        for (TRegisterPaymentOrderVo orderVo : orderVoList) {
            closeOrder(orderVo.getId());
        }
    }

    @Override
    public List<TRegisterWillExpirationOrderVo> queryWillExpirationOrder() throws Exception {
        return baseMapper.queryWillExpirationOrder();
    }

    // 处理审批
    @Transactional
    @Override
    public void processApproval(String approvalId, Integer status, String opinion) throws Exception {

        // 流程中心任务审批
        flowService.processApproval(approvalId, status, opinion);

        // 检查整个审批流程状态
        checkApprovalProcessStatus(approvalId);
    }

    // 检查审批流程状态
    private void checkApprovalProcessStatus(String approvalId) throws Exception {
        List<TRegisterApprovalFlowVo> flows = flowService.getAllApprovalFlowByApproval(approvalId);
        // 检查是否有拒绝的情况
        for (TRegisterApprovalFlow flow : flows) {
            if (flow.getStatus() == ApprovalFlowStatus.REJECTED.getCode()) {
                // 审批拒绝，更新退款申请状态
                updatePaymentOrderStatus(flow.getBusinessId(), OrderRefundStatus.REJECTED);
                return;
            }
        }

        // 检查是否所有级别都已通过
        boolean allApproved = true;
        int currentLevel = 1;
        for (TRegisterApprovalFlow flow : flows) {
            if (flow.getApprovalLevel() != currentLevel) {
                throw new IllegalStateException("审批级别顺序异常");
            }
            if (flow.getStatus() != ApprovalFlowStatus.APPROVED.getCode()) {
                allApproved = false;
                break;
            }
            currentLevel++;
        }

        // 获取匹配到审批对象的数据
        TRegisterApprovalFlowVo approvalFlowVo = flows.stream()
                .filter(flow -> StringUtils.equals(String.valueOf(flow.getApprovalId()), approvalId))
                .findFirst()
                .orElse(null);
        if(approvalFlowVo == null){
            throw new BaseException("获取不到审批对象");
        }
        if (!allApproved) {
            // 部分通过，更新退款申请状态为审批中
            updatePaymentOrderStatus(approvalFlowVo.getBusinessId(), OrderRefundStatus.IN_APPROVAL);
        }
        if (allApproved) {
            // 提交到支付中心退款申请
            executeRefund(approvalFlowVo.getBusinessId());
        }
    }

    // 执行退款
    private void executeRefund(String refundId) throws Exception {
        // 获取退款申请
        QueryWrapper<TRegisterPaymentOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("refund_id", refundId);
        List<TRegisterPaymentOrder> orderList = baseMapper.selectList(queryWrapper);
        if (orderList == null || orderList.isEmpty()) {
            throw new BaseException("退款申请不存在");
        }
        TRegisterPaymentOrder paymentOrder = orderList.get(0);
        // 调用支付渠道执行退款
        // 6.提交订单到支付中心
        JSONObject submitJson = new JSONObject();
        submitJson.put("busNo", String.valueOf(paymentOrder.getId()));
        submitJson.put("busDate", DateUtil.format(paymentOrder.getCreateTime(), "yyyy-MM-dd"));
        submitJson.put("refundBusNo", paymentOrder.getRefundId());
        submitJson.put("refundDateTime", DateUtil.format(new Date(), "yyyyMMddHHmmssSSS"));
        submitJson.put("refundTotalAmount", paymentOrder.getRefundAmount());
        submitJson.put("refundReason", paymentOrder.getRefundReason());
        submitJson.put("notifyUrl", paymentConfig.getRefundNotifyUrl());
        submitJson.put("operator", paymentConfig.getOperator());
        submitJson.put("templateCode", paymentConfig.getTemplateCode());
        JSONArray chargeDetailArr = new JSONArray();
        JSONObject chargeDetail = new JSONObject();
        chargeDetail.put("chargeCode", paymentConfig.getChargeCode());
        chargeDetail.put("refundAmt", paymentOrder.getRefundAmount());
        chargeDetailArr.add(chargeDetail);
        submitJson.put("chargeDetail", chargeDetailArr);
        thirdPaymentService.submitReturnOrder(submitJson.toJSONString());
        // 更新申请状态
        paymentOrder.setRefundStatus(OrderRefundStatus.EXECUTING.getCode());
        paymentOrder.setPaymentStatus(PaymentOrderStatus.REFUNDING.getCode());
        baseMapper.updateById(paymentOrder);
    }

    // 更新退款申请状态
    private void updatePaymentOrderStatus(String refundId, OrderRefundStatus status) {
        QueryWrapper<TRegisterPaymentOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("refund_id", refundId);
        List<TRegisterPaymentOrder> orderList = baseMapper.selectList(queryWrapper);
        if (orderList != null) {
            for (TRegisterPaymentOrder paymentOrder : orderList) {
                paymentOrder.setRefundStatus(status.getCode());
                paymentOrder.setUpdateTime(DateUtils.getNowDate());
                baseMapper.updateById(paymentOrder);
            }
        }
    }


}
